<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="">
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出商品数据</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link>
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="{ row }">
        <el-button type="primary" link :icon="Sell" :disabled="row.state !== 1" @click="openDrawer(row)">发货</el-button>
        <el-button type="danger" link :icon="Delete" @click="deleteAccount(row)">删除</el-button>
        <el-button type="warning" link :icon="Files" @click="reunfAccount(row)">退款</el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive } from "vue";
import { Items, Order } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownloads } from "@/hooks/useDownload";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Sell, Files } from "@element-plus/icons-vue";
import { OrderById, OrderExport, OrderList, OrderRefund, OrderShip } from "@/api/modules/order";

import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total
  };
};

const getTableList = (params: any) => {
  showFullScreenLoading(); // 👈 开启 loading
  let newParams = JSON.parse(JSON.stringify(params));
  tryHideFullScreenLoading(); // 👈 关闭 loading
  return OrderList(newParams);
};
// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<Order.OrderName>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success(`已复制`);
  } catch (err) {}
};
// 表格配置项
const columns = reactive<ColumnProps<Order.OrderName>[]>([
  { type: "selection", fixed: "left", width: 50 },
  { prop: "id", label: "id" },
  {
    prop: "orderName",
    label: "商品标题",
    search: { el: "input", tooltip: "我是搜索提示" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.orderName.toString())}>
          {scope.row.orderName}
        </el-button>
      );
    }
  },
  {
    prop: "orderNo",
    label: "订单编号",
    search: { el: "input" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.orderNo.toString())}>
          {scope.row.orderNo}
        </el-button>
      );
    }
  },
  { prop: "payPrice", label: "总价" },
  { prop: "postFee", label: "邮费" },
  {
    prop: "createTime",
    label: "创建时间",
    headerRender
  },
  {
    prop: "paymentTime",
    label: "支付时间",
    headerRender
  },
  {
    prop: "state",
    label: "支付状态",
    render: scope => {
      const stateMap: Record<number, { text: string; color: string }> = {
        1: { text: "已支付", color: "green" },
        2: { text: "未支付", color: "orange" },
        3: { text: "已取消", color: "black" },
        4: { text: "已发货", color: "black" },
        5: { text: "已完成", color: "black" },
        6: { text: "退款中", color: "red" }
      };
      const current = stateMap[scope.row.state] || { text: "未知", color: "gray" };

      return <span style={{ color: current.color }}>{current.text}</span>;
    }
  },
  { prop: "username", label: "购买人" },
  { prop: "operation", label: "操作", fixed: "right", width: 300 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除商品信息
const deleteAccount = async (params: Order.OrderName) => {
  await useHandleData(OrderById, params.id, `删除【${params.orderName}】订单`);
  proTable.value?.getTableList();
};

// 导出商品列表
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownloads(OrderExport, "订单列表", proTable.value?.searchParam)
  );
};

// 退款
const reunfAccount = async (params: Order.OrderName) => {
  await useHandleData(OrderRefund, params.orderNo, `是否退款【${params.orderNo}】订单编号`);
  proTable.value?.getTableList();
};
// 发货
const openDrawer = async (parmas: Order.OrderName) => {
  await useHandleData(OrderShip, parmas.orderNo, `确认是否发货？`);
  proTable.value?.getTableList();
};
</script>
